package com.gxa.controller.admin;

import com.gxa.common.R.ResponseData;
import com.gxa.realm.MyRealm;
import com.gxa.utils.JwtUtils;
import io.swagger.annotations.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

@Api(value = "登录",tags = "登录API")
@Controller
public class LoginController {

    @Autowired
    private MyRealm myRealm;

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    @ResponseBody
    @ApiResponses({
            @ApiResponse(code=200,message="请求成功"),
            @ApiResponse(code=500,message="用户名或密码错误")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name ="number",value = "账户名",dataType = "String",required = true),
            @ApiImplicitParam(name ="password",value = "密码",dataType = "String",required = true)
    })
    public ResponseData login(@RequestParam(name = "number")String number,
                              @RequestParam(name = "password")String password){
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();

        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(1024);
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        defaultSecurityManager.setRealm(myRealm);
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(number,password);
        subject.login(token);
        System.out.println(subject.isAuthenticated());

        ResponseData responseData = new ResponseData();
        if(subject.isAuthenticated()){
            String jwtToken= JwtUtils.createJwt(UUID.randomUUID().toString(),
                    "gxa_jwt_test",JwtUtils.generalSubject(number),JwtUtils.TTMILLIS);
            responseData.setCode(200);
            responseData.setMsg("登陆成功");
            responseData.setToken(jwtToken);
            return responseData;
        }else {
            responseData.setCode(506);
            responseData.setMsg("登陆失败");
            return responseData;
        }

    }
}
